<script setup>
import { ref, reactive, inject, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useConfigStore } from '@/stores/config'
import userApi from '@/apis/user'

import ImgCaptcha from '@/components/form/imgCaptcha.vue'
import SendCaptcha from '@/components/user/SendCaptcha.vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const configStore = useConfigStore()

const agreement = inject('showAgreement')
const closed = computed(() => configStore.get('user.register_closed', false))
const captchaFields = computed(() => {
  let fields = []
  ;['mobile', 'email'].forEach((element) => {
    if (configStore.get(`user.${element}_feature`, []).includes('register')) {
      fields.push(element)
    }
  })
  return fields
})

const form = ref(null)
const captchaRef = ref(null)
const model = ref({
  username: '',
  password: '',
  confirmPassword: '',
  agreement: [],
  invite: '',
})
const rules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    //必须超过6个字符吗，并要求包含数字和字母
    {
      validator: (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码必须超过6个字符'))
        } else if (!/[a-zA-Z]/.test(value) || !/[0-9]/.test(value)) {
          callback(new Error('密码必须包含数字和字母'))
        } else {
          callback()
        }
      },
    },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== model.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
    },
  ],
  agreement: [{ required: true, message: '请先阅读并同意协议内容', trigger: 'change' }],
})

if (captchaFields.value.includes('mobile')) {
  rules.mobile = [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      },
    },
  ]
  rules.smsCaptcha = [
    { required: true, message: '请输入手机验证码', trigger: 'blur' },
    //验证码格式为4个数字
    {
      validator: (rule, value, callback) => {
        if (value.length !== 4 || !/^\d+$/.test(value)) {
          callback(new Error('手机验证码格式错误'))
        } else {
          callback()
        }
      },
    },
  ]
  model.value.mobile = ''
  model.smsCaptcha = ''
}
if (captchaFields.value.includes('email')) {
  rules.email = [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      },
    },
  ]
  rules.emsCaptcha = [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    //验证码格式为4个数字
    {
      validator: (rule, value, callback) => {
        if (value.length !== 4 || !/^\d+$/.test(value)) {
          callback(new Error('邮箱验证码格式错误'))
        } else {
          callback()
        }
      },
    },
  ]
  model.value.email = ''
  model.emsCaptcha = ''
}
if (captchaFields.value.length === 0) {
  model.value.captcha = ''
  rules.captcha = [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}
/**
 * 提交表单
 * @returns {Promise<void>}
 */
const submitForm = async () => {
  await form.value.validate(async (valid) => {
    if (valid) {
      try {
        const { data } = await userApi.passport.register(model.value)
        authStore.setAuth(data)
        ElMessage.success('注册成功')
        //获取路由上的redirect参数
        const path = decodeURIComponent(route.query?.redirect || '/user')
        //跳转到登录成功页面
        await router.replace(path)
      } catch (e) {
        console.log('注册失败', e)
        if (captchaRef.value) captchaRef.value.getCaptcha()
      }
    } else {
      console.log('验证失败')
      return false
    }
  })
}

/**
 * 获取query参数code
 * 并保存到localStorage中
 */
const getQueryCode = () => {
  let code = ''
  const query = route.query
  if (route.query?.invite) {
    code = query.invite
    sessionStorage.setItem('inviteCode', query.invite)
  } else {
    code = sessionStorage.getItem('inviteCode') || ''
  }
  //邀请码放入提交表单里
  if (code) {
    model.value.invite = code
  }
}

onMounted(getQueryCode)
</script>

<template>
  <div class="text-center font-bold text-2xl">用户注册</div>
  <div class="flex-1 mt-5 space-y-5" v-if="!closed">
    <el-form ref="form" :model="model" label-width="auto" :rules="rules">
      <el-form-item label="账号" prop="username">
        <el-input v-model="model.username" placeholder="请输入账号名称" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="model.password" placeholder="请输入登录密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="model.confirmPassword" placeholder="请再次输入密码" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile" v-if="captchaFields.includes('mobile')">
        <el-input v-model="model.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="验证码" prop="smsCaptcha" v-if="captchaFields.includes('mobile')">
        <el-input v-model="model.smsCaptcha" placeholder="请输入手机验证码">
          <template #append>
            <SendCaptcha type="mobile" :account="model.mobile" event="register" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email" v-if="captchaFields.includes('email')">
        <el-input v-model="model.email" placeholder="请输入邮箱地址" />
      </el-form-item>
      <el-form-item label="验证码" prop="emsCaptcha" v-if="captchaFields.includes('email')">
        <el-input v-model="model.emsCaptcha" placeholder="请输入邮箱验证码">
          <template #append>
            <SendCaptcha type="email" :account="model.email" event="register" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="captcha" v-if="!captchaFields.length">
        <el-input v-model="model.captcha" placeholder="请输入验证码">
          <template #suffix>
            <ImgCaptcha ref="captchaRef" class="w-18 h-8 sm:h-[30px] object-contain" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="&nbsp;" prop="agreement">
        <el-checkbox-group v-model="model.agreement">
          <div class="flex justify-between items-center">
            <el-checkbox value="1" name="agreement">
              <span class="text-[--el-text-color-secondary] text-xs font-normal">
                我已经阅读并同意<span class="agreement-link" @click="agreement('agreement')"
                  >用户协议</span
                >和<span class="agreement-link" @click="agreement('privacy')">隐私政策</span>
              </span>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" @click="submitForm">
          <FontAwesomeIcon icon="sign-in-alt" />
          <span class="pl-1">注册</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div v-else class="py-10 text-center text-[--el-text-color-primary]">
    <p class="mb-10 text-[--el-color-warning]">
      <FontAwesomeIcon icon="info-circle" size="4x" />
    </p>
    <p>抱歉，注册功能已关闭。</p>
  </div>
</template>

<style scoped>
.agreement-link {
  @apply text-[--el-color-primary] cursor-pointer;
}
</style>
